﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        Assembly ass;
        Type type;
        object obj;
        /// <summary>
        /// 调用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string meth = methList.SelectedItem?.ToString();
            if (!string.IsNullOrEmpty(meth))
            {
                try
                {
                    //获取类的方法：方法名称
                    MethodInfo method1 = type.GetMethod(meth);
                    obj = Activator.CreateInstance(type);
                    method1.Invoke(obj, null);
                    MessageBox.Show("调用完成。" );
                }
                catch (Exception ex)
                {
                    MessageBox.Show("调用出错："+ex);
                }
            }
            else
            {
                MessageBox.Show("请新选择要调用的dll方法");
            }
        }


        /// <summary>
        /// 选择文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "所有文件 (*.*)|*.dll";
            if (openFileDialog.ShowDialog() == true)
            {
                // 用户选择了文件
                string filename = openFileDialog.FileName;
                ass = Assembly.LoadFrom(filename);
                dllpath.Text = filename;
                classList.ItemsSource = ass.GetTypes().ToList().Select(c => c.ToString()).ToList();
            }
        }

        private void classList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string fullSpace = classList.SelectedItem?.ToString();
            if (!string.IsNullOrEmpty(fullSpace))
            {
                //获取类的类型：必须使用名称空间+类名称
                type = ass.GetType(fullSpace);
                methList.ItemsSource = type.GetMethods().ToList().Select(c => c.Name).ToList();
            }
        }

        private void methList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
    }
}
